package com.yuelan.codelib.download;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.WindowManager;

import com.yuelan.codelib.utils.ImageDownloader;
import com.yuelan.codelib.utils.ImageDownloader.OnImageDownload;
import com.yuelan.codelib.utils.LOG;
import com.yuelan.codelib.utils.MathUtil;
import com.yuelan.codelib.utils.TextUtil;

public class TpService extends Service {
	public final static int Index_Id = 0; // [gameid]
	public final static int Index_Step = 1; // []
	public final static int Index_DownFileSize = 2; // [下载了多少]
	public final static int Index_ToDownFileSize = 3; // [downloadfilesize要下载多少]
	public final static int Index_Name = 4; // [name]
	public final static int Index_Url = 5; // [url]
	public final static int Index_AdId = 6; // [adid]
	public final static int Index_PackageName = 7; // [packagename]
	public final static int Index_Popuptype = 8; // [popuptype]
	public final static int Index_Popuptext = 9; // [popupText]
	public final static int Index_Filepath = 10; // [filepath]
	public final static int Index_DummySize = 11; // [appsize]
	public final static int Index_Type = 12; // [type]
	public final static int Index_PageId = 13; // [pageid]
	public final static int Index_DlCallBackUrl = 14; // [pageid]

	public static final String ACTION_DOWNLOAD_BASIC = "download_basic";
	public static final String ACTION_DOWNLOAD_AP = "download_ap";

	private TpDB db;
	private ArrayList<TpInfo> infos;
	private ArrayList<String> infos_download;
	private ProgressBroadCastReceive myBroadCast;
	private TpNfView dnv;

	public static String getBROADCAST_DOWNLOAD_OK(Context c) {
		return c.getPackageName() + "broadcast_download_ok";
	}

	public IBinder onBind(Intent intent) {
		return null;
	}

	public void onCreate() {
		db = new TpDB(this);
		dnv = new TpNfView(this);
		infos_download = new ArrayList<String>();
		myBroadCast = new ProgressBroadCastReceive();
		this.registerReceiver(myBroadCast,
				new IntentFilter(TpUtil.getACTION_DOWNLOAD(this)));
	}

	public void onDestroy() {
		this.unregisterReceiver(myBroadCast);
	}

	class ProgressBroadCastReceive extends BroadcastReceiver {

		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(TpUtil.getACTION_DOWNLOAD(context))) {
				String info = intent.getStringExtra("info");
				Message msg = new Message();
				msg.obj = info;
				hanlder_change.sendMessage(msg);
			}
		}
	}

	public Handler hanlder_change = new Handler() {

		public void handleMessage(Message msg) {
			try {
				String obj = (String) msg.obj;
				LOG.v(obj);
				final String[] array = obj.split("#_#");
				int id = Integer.parseInt(array[Index_Id]);
				final double finalPercent = (Double
						.parseDouble(array[Index_DownFileSize]) / Double
						.parseDouble(array[Index_ToDownFileSize])) * 100;
				// LOG.v(array[Index_DownFileSize] + "---------");
				// LOG.v(array[Index_ToDownFileSize] + "---------");
				LOG.v(finalPercent + "---------");
				if (array[Index_Step].equals("NO")) {
					// LOG.v("hanlder_change NO");
					int state = -1;
					String sql = "update download_info set state = ?,downloadfilesize = ? where gameid = ? and packagename = ? ";
					db.execSQL(sql, new Object[] { state + "",
							array[Index_DownFileSize] + "", id + "",
							array[Index_PackageName] });
					LOG.v("array[Index_PackageName]" + array[Index_PackageName]);
					Intent intent = new Intent(TpService.this, TpService.class);
					intent.putExtra("id", array[Index_Id]);
					intent.putExtra("packagename", array[Index_PackageName]);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.setAction(ACTION_DOWNLOAD_AP);
					final PendingIntent pendingIntent = PendingIntent
							.getService(TpService.this,
									Integer.parseInt(array[Index_Id]), intent,
									0);
					if (array[Index_Type].equals("1")) {
						LOG.v("nnnnnnnnnnnnnnnnn" + array[Index_Type]);
						ImageDownloader.imageDownload(array[Index_Url],
								TpService.this, new OnImageDownload() {

									public void onDownloadSucc(
											Bitmap imageDrawable) {
										dnv.showDownloadView(
												array[Index_Name],
												0,
												imageDrawable,
												"点击重试",
												(int) finalPercent,
												"下载失败",
												Integer.parseInt(array[Index_Id]),
												pendingIntent, true);
									}
								}, 200);
					}
				} else if (array[Index_Step].equals("YES")) {
					String filePath = array[Index_Filepath];
					File apkFile = new File(filePath);
					LOG.v(apkFile + "apkFile");
					if (apkFile.exists()) {
						// 发送广播
						String cmd = "chmod 777 " + filePath;
						try {
							Runtime.getRuntime().exec(cmd);
						} catch (IOException e) {
							e.printStackTrace();
						}
						TpService.this.sendBroadcast(new Intent(
								getBROADCAST_DOWNLOAD_OK(TpService.this)));
						final Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.setDataAndType(Uri.fromFile(apkFile),
								"application/vnd.android.package-archive");
						final PendingIntent pendingIntent = PendingIntent
								.getActivity(TpService.this,
										Integer.parseInt(array[Index_Id]),
										intent, 0);
						if (array[Index_Popuptype].equals("2")) {
							intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							startActivity(intent);
							Intent it = new Intent(
									Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
							sendBroadcast(it);
						} else if (array[Index_Popuptype].equals("3")) {
							Dialog alertDialog = new AlertDialog.Builder(
									TpService.this)
									.setCancelable(false)
									.setPositiveButton("确定",
											new OnClickListener() {

												public void onClick(
														DialogInterface arg0,
														int arg1) {
													intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
													startActivity(intent);
												}
											})
									.setMessage(array[Index_Popuptext])
									.create();
							alertDialog
									.getWindow()
									.setType(
											WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
							alertDialog.show();
						}
						if (array[Index_Type].equals("1")) {
							ImageDownloader.imageDownload(array[Index_Url],
									TpService.this, new OnImageDownload() {

										public void onDownloadSucc(
												Bitmap imageDrawable) {
											dnv.showDownloadView(
													array[Index_Name],
													0,
													imageDrawable,
													"点击立即安装",
													100,
													"下载完成",
													Integer.parseInt(array[Index_Id]),
													pendingIntent, true);
										}
									}, 200);
						}
						// 下载成功统计
						// DBUtil.appDownload(TpService.this,
						// Integer.valueOf(array[Index_AdId]),
						// array[Index_Id],
						// Integer.valueOf(array[Index_PageId]));
						int state = 1;
						String sql = "update download_info set state = ?,downloadfilesize = ? where gameid = ? and packagename = ? ";
						db.execSQL(sql, new Object[] { state + "",
								array[Index_ToDownFileSize] + "", id + "",
								array[Index_PackageName] });
					}
				} else {
					final String appDummySize = array[Index_DummySize];
					if (array[Index_Type].equals("1")) {
						LOG.v("zzzzzzzzzzzzzz" + array[Index_Type]);
						ImageDownloader.imageDownload(array[Index_Url],
								TpService.this, new OnImageDownload() {

									public void onDownloadSucc(
											Bitmap imageDrawable) {
										dnv.showDownloadView(
												array[Index_Name],
												0,
												imageDrawable,
												(MathUtil.roundDouble(
														finalPercent
																* 0.01
																* Double.parseDouble(appDummySize),
														2))
														+ "M/"
														+ appDummySize
														+ "M",
												(int) finalPercent,
												"正在下载",
												Integer.parseInt(array[Index_Id]),
												null, true);
									}
								}, 200);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	public int onStartCommand(Intent intent, int flags, int startId) {
		if (intent != null && TextUtil.notNull(intent.getAction())) {
			if (intent.getAction().equals(ACTION_DOWNLOAD_BASIC)) {
				checkDBToDownload();
				goToDownload(infos.get(0), 0);
			} else if (intent.getAction().equals(ACTION_DOWNLOAD_AP)) {
				final String appid = intent.getStringExtra("id");
				final String packagename = intent.getStringExtra("packagename");
				if (TextUtil.notNull(appid)) {
					int state = 0;
					String sql_update = "update download_info set state = ? where gameid = ?and packagename = ? ";
					db.execSQL(sql_update, new Object[] { state + "",
							appid + "", packagename });
					final TpInfo downloadInfo = db.getDownloadInfoForId(appid,
							packagename);
					if (downloadInfo != null) {
						String downloadFileSize = downloadInfo
								.getDownloadFileSize();
						String totalFileSize = downloadInfo.getTotalFileSize();
						final double finalPercent = (Double
								.parseDouble(downloadFileSize) / Double
								.parseDouble(totalFileSize)) * 100;
						final String appDummySize = downloadInfo
								.getAppDummySize();
						if (downloadInfo.getType() == 1) {
							ImageDownloader.imageDownload(
									downloadInfo.getIconUrl(), TpService.this,
									new OnImageDownload() {

										public void onDownloadSucc(
												Bitmap imageDrawable) {
											dnv.showDownloadView(
													downloadInfo.getName(),
													0,
													imageDrawable,
													(MathUtil.roundDouble(
															finalPercent
																	* 0.01
																	* Double.parseDouble(appDummySize),
															2))
															+ "M/"
															+ appDummySize
															+ "M",
													(int) finalPercent, "等待下载",
													Integer.valueOf(appid),
													null, false);
										}
									}, 200);
						}
						checkDBToDownload();
						goToDownload(infos.get(0), 0);
					}
				}
			}
		}
		return super.onStartCommand(intent, flags, startId);
	}

	private void checkDBToDownload() {
		TpInfo info = null;
		String sql = "select * from download_info ";
		infos = new ArrayList<TpInfo>();
		if (db == null) {
			db = new TpDB(this);
		}
		Cursor cusor = db.query(sql, null);
		while (cusor.moveToNext()) {
			info = new TpInfo();
			int state = Integer.valueOf(cusor.getString(TpDB.Index_State));
			if (state == 0 || state == -1) {
				info.setState(state);
				info.setUrl(cusor.getString(TpDB.Index_Url));
				info.setId(cusor.getString(TpDB.Index_Id));
				info.setName(cusor.getString(TpDB.Index_Name));
				info.setType(Integer.parseInt(cusor.getString(TpDB.Index_Type)));
				info.setFilePath(cusor.getString(TpDB.Index_Filepath));
				info.setIconUrl(cusor.getString(TpDB.Index_IconUrl));
				info.setAdid(Integer.parseInt(cusor.getString(TpDB.Index_AdId)));
				info.setPackageName(cusor.getString(TpDB.Index_PackageName));
				info.setPopupType(cusor.getString(TpDB.Index_Popuptype));
				info.setPopupText(cusor.getString(TpDB.Index_Popuptext));
				info.setAppDummySize(cusor.getString(TpDB.Index_DummySize));
				info.setPageid(Integer.parseInt(cusor
						.getString(TpDB.Index_PageId)));
				info.setCrc32(cusor.getLong(TpDB.Index_Crc32));
				info.setDlCallBackUrl(cusor.getString(TpDB.Index_DlCallBackUrl));
				infos.add(info);
			}
		}
		cusor.close();
	}

	private void goToDownload(final TpInfo info, final int i) {
		// LOG.v("goToDownload i = " + i + ", getState() = " + info.getState()
		// + ", getName() = " + info.getName());
		if (info.getState() == -1) {
			int next = i + 1;
			if (next < infos.size()) {
				goToDownload(infos.get(next), next);
			}
		} else {
			if (infos_download.contains(info.getId()) == false) {
				infos_download.add(info.getId());
				new Thread(new Runnable() {

					public void run() {
						String filename = info.getName() + ".";
						TpUtil.doHttpDownloadApk(info.getUrl(),
								info.getFilePath() + filename, info.getType(),
								TpService.this, info.getId(), db,
								info.getName(), info.getIconUrl(),
								info.getAdid(), info.getPackageName(),
								info.getPopupType(), info.getPopupText(),
								info.getAppDummySize(), info.getPageid(),
								info.getCrc32(), info.getDlCallBackUrl(), 0);
						// LOG.v("goToDownload end");
						infos_download.remove(info.getId());
						int next = i + 1;
						if (next < infos.size()) {
							goToDownload(infos.get(next), next);
						}

					}
				}).start();
			}
		}
	}

}
